<template>
  <div class="app-container">
    <Header title="问答"></Header>
    <div class="empty"></div>
    <ChatFlex :messages="messageList"></ChatFlex>
    <van-cell-group inset>
      <van-field class="input" v-model="input" placeholder="输入问题" input-align="left">
        <template #button>
          <van-button :disabled="!buttonEnable" size="small" type="primary" @click="onsetMessageList">发送</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div class="empty" style="height: 90px"></div>
  </div>
</template>

<script>
import ChatFlex from "@/components/Chat/ChatFlex.vue";
import Header from "@/components/Header/Header.vue";
import AiTool from "@/server/AiTool.js"
import bus from '@/utils/eventBus.js'

export default {
  name: "Question",
  data() {
    return {
      aitool: null,
      messageList: [],
      input: "",
      buttonEnable: true,
    };
  },
  methods: {
    async onsetMessageList() {
      if (this.input !== null && this.input !== "") {
        // 聊天内容
        this.messageList = [{ content: this.input, role: "user" }, ...this.messageList];
        // 输入框置空
        const questionText = this.input;
        this.input = "";
        // 按钮禁用
        this.buttonEnable = false;
        // 等待回答
        this.messageList = [{ content: "等待回答。。。", role: "assistant" }, ...this.messageList];
        await this.aitool.sendMsg(questionText)
      }
    }
  },
  mounted() {
    bus.on("init-hoodle", (msg) => {
      for (let i = 0; i < msg.length; i++) {
        this.messageList = [msg[i], ...this.messageList]
      }
    })
    bus.on("respond-hoodle", (result) => {
      this.messageList[0].content = result
    })
    bus.on("load-hoodle", (load) => {
      if (!load) {
        this.buttonEnable = true;
      }
    })
    this.aitool = new AiTool()
  },
  components: {
    Header,
    ChatFlex,
  },
};
</script>

<style lang="less" scoped>
.app-container {
  background-color: rgb(232, 255, 221);
  height: 100vh;
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  .empty {
    height: 70px;
    width: 100%;
    background-color: rgb(232, 255, 221);
  }
}

.input {
  width: 366px;
  background-color: #fff;
  height: 76px;
  cursor: pointer;
  border-radius: 4px;
}
</style>
